import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

public class ConnectionReader extends Thread {
	private Connection connection;
	private Socket socket;
	private ObjectInputStream inStream; 
	private Klientobsluga klient;
	private Message m;
	
	public ConnectionReader(Connection c, Klientobsluga s) {
		klient = s;
		socket = c.socket;
		try {
		inStream = new ObjectInputStream(socket.getInputStream()); 
		} catch(Exception e) { System.out.println(e.getMessage()); }
	System.out.println("connection reader started");
	
	}
	
	protected Message getMessage() {
		Message m = null;
		try {
			//inStream.mark();
			//inStream.reset();
			m = (Message) inStream.readObject();
		} catch (IOException e2) { //awaria
				System.out.println(e2.getMessage() + "AAAAAAAAAAAA");
				connection.invokeLater(new Runnable() {
					public void run() {
						connection.connectionClosed();
					}
				});
		} catch (Exception e) { System.out.println(e.getMessage()); }
		return m;
	}
	
	public void handleMessage(Message m) {
		klient.handleMessage(m);
	}
	
	public void run() {
		while(true) {
			System.out.println("waiting");
				Message m = getMessage();
				this.handleMessage(m);

				
			//	if(m.getType() == Message.AWARIA)
			//	{
			//		klient.s;
			//		break ;
			//	}
					
		}
	}
}